import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class LeetCode1679 {

    public int maxOperations(int[] nums, int k) {
        int result = 0;
        if(nums.length < 2){
            return result;
        }
        Arrays.sort(nums);

        int leftIndex = 0;
        int rightIndex = nums.length - 1;
        while (leftIndex < rightIndex){
            if(nums[leftIndex] + nums[rightIndex] > k){
                rightIndex--;
                continue;
            }
            if(nums[leftIndex] + nums[rightIndex] < k){
                leftIndex++;
                continue;
            }
            rightIndex--;
            leftIndex++;
            result++;

        }
        return result;
    }

    /**
     * 111011111101010101001010100011111
     * 1.右侧指针right找到第k+1个0，并记录当前right - left + 1作为当前范围内的长度sum
     * 2.当right到达第k+1个0后，left指针移到离它右侧最近的一个0的下一个索引位置，然后执行1操作
     * @param nums
     * @param k
     * @return
     */
    public static int longestOnes(int[] nums, int k) {
        int left = 0;
        int right = 0;
        int sum = 0;
        int kNum = 0;
        for(int i = 0; i < nums.length; i++){
            if(nums[i] == 0){
                kNum++;
            }

            if(kNum == k + 1){
                right = i;
                sum = Math.max(sum, right - left);
                System.out.println("left:" + left + "  right:" + right);

                while (kNum > k && left < nums.length && right < nums.length){

                    if(nums[left] == 0){
                        left++;
                        kNum--;
                        break;
                    }
                    left++;
                }
            }
        }

        right = nums.length;
        System.out.println("left:" + left + "  right:" + right);
        sum = Math.max(sum, right - left);
        return sum;
    }

    public static void main(String[] args) {
        System.out.println(longestOnes(new int[]{1,1,1,0,0,0,1,1,1,1,0}, 2));
        System.out.println("------------------------------------");
        System.out.println(longestOnes(new int[]{0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1}, 3));
    }


}
